package com.hskn.hss.module.kfkdeal.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.entity.AbnormalResult;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.dlbjviolation.entity.DlbjViolation;
import com.hskn.hss.module.dlbjviolation.mapper.DlbjViolationMapper;
import com.hskn.hss.module.employeePunchCard.entity.EmployeePunchCard;
import com.hskn.hss.module.employeePunchCard.mapper.EmployeePunchCardMapper;
import com.hskn.hss.module.employeePunchCard.service.EmployeePunchCardService;
import com.hskn.hss.module.employeeTrack.entity.EmployeeTrack;
import com.hskn.hss.module.employeeTrack.mapper.EmployeeTrackMapper;
import com.hskn.hss.module.grid.entity.Grid;
import com.hskn.hss.module.grid.mapper.GridMapper;
import com.hskn.hss.module.gridBindCheckWork.entity.GridBindCheckwork;
import com.hskn.hss.module.gridBindCheckWork.service.GridBindCheckWorkService;
import com.hskn.hss.module.gridbind.mapper.GridBindMapper;
import com.hskn.hss.module.kfkdeal.entity.car.kfkDealCarWorkPlan;
import com.hskn.hss.module.kfkdeal.service.IkfkDealService;
import com.hskn.hss.module.kfkdeal.to.KfkDealEmployeeTo;
import com.hskn.hss.module.role.entity.SysRole;
import com.hskn.hss.module.role.mapper.SysRoleMapper;
import com.hskn.hss.module.rptEmployeeWork.entity.RptEmployeeWork;
import com.hskn.hss.module.rptEmployeeWork.mapper.RptEmployeeWorkMapper;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlfacilities.entity.TlFacilities;
import com.hskn.hss.module.tlfacilities.mapper.TlFacilitiesMapper;
import com.hskn.hss.module.tlthreshold.entity.TlThreshold;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.module.tlworktype.entity.TlWorkType;
import com.hskn.hss.module.tlworktype.mapper.TlWorkTypeMapper;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.userrole.entity.SysUserRole;
import com.hskn.hss.module.userrole.mapper.SysUserRoleMapper;
import com.hskn.hss.module.workgroup.entity.WorkGroup;
import com.hskn.hss.module.workgroup.mapper.WorkGroupMapper;
import com.hskn.hss.module.workgroup.service.IWorkGroupService;
import com.hskn.hss.module.workkaoqin.entity.WorkKaoqin;
import com.hskn.hss.module.workkaoqin.mapper.WorkKaoqinMapper;
import com.hskn.hss.module.workruleitem.entity.WorkRuleItem;
import com.hskn.hss.utils.*;
import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class KfkDealServiceImpl implements IkfkDealService {
    @Resource
    GridMapper gridMapper;
    @Autowired
    LocationUtils locationUtil;
    @Autowired
    WorkUtil workUtil;
    @Resource
    TlThresholdMapper tlThresholdMapper;
    @Resource
    EmployeeTrackMapper employeeTrackMapper;
    @Resource
    private RptEmployeeWorkMapper rptEmployeeWorkMapper;
    @Resource
    private WorkKaoqinMapper workKaoqinMapper;
    @Resource
    private WorkGroupMapper workGroupMapper;
    @Resource
    private IWorkGroupService workGroupService;
    @Resource
    private TlEmployeeMapper tlEmployeeMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;
    @Resource
    private DlbjViolationMapper dlbjViolationMapper;
    @Resource
    private TlWorkTypeMapper tlWorkTypeMapper;
    @Resource
    private TlFacilitiesMapper tlFacilitiesMapper;
    @Autowired
    private KfkHandleServiceImpl kfkHandleService;
    @Resource
    private GridBindMapper gridBindMapper;
    @Resource
    private EmployeePunchCardMapper employeePunchCardMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GridBindCheckWorkService gridBindCheckWorkService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private EmployeePunchCardService employeePunchCardService;

    @Override
    public void KfkDealEmployee(KfkDealEmployeeTo kfkDealEmployeeTo) {
        EmployeeTrack newEmployeeTrack = crateEmployeeTrack(kfkDealEmployeeTo);
        Boolean isInsert = true;
        boolean is_in_worktime = false;
        boolean is_in_grid = false;
        try {
            List<Grid> gridList = gridMapper.selectList(new QueryWrapper<>());
            Map<String, Grid> gridMap = gridList.stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(toList(), grids -> grids.get(0))));

            List<TlEmployee> tlEmployeeListOne = tlEmployeeMapper.selectList(new QueryWrapper<>());
            Map<String, TlEmployee> tlEmployeeMap = tlEmployeeListOne.stream().collect(Collectors.groupingBy(TlEmployee::getId, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0))));


            //在这里只判断移动
            TlEmployee tlEmployee = tlEmployeeMapper.selectById(kfkDealEmployeeTo.getEmployee_id());

//            //打卡
//            employeePunchCardService.punchCard(kfkDealEmployeeTo, tlEmployee);

            EmployeeTrack lastEmployeeTrack = RedisUtil.get(EmployeeTrackLastOneKeyToday.token, newEmployeeTrack.getEmployeeId(), EmployeeTrack.class);

            if (Objects.isNull(lastEmployeeTrack)) {
                lastEmployeeTrack = setLastEmployeeTrack(tlEmployee, newEmployeeTrack);
            }

            if (newEmployeeTrack.getTimestamp().equals(lastEmployeeTrack.getTimestamp()) && newEmployeeTrack.getEmployeeId().equals(lastEmployeeTrack.getEmployeeId()) && newEmployeeTrack.getLocation().equals(lastEmployeeTrack.getLocation())
                    && newEmployeeTrack.getSpeed().equals(lastEmployeeTrack.getSpeed())) {
                isInsert = false;
                return;
            }
            // 计算当前坐标和上一次坐标的距离
            double towPointDistance = locationUtil.getDistance(newEmployeeTrack.getLat(), newEmployeeTrack.getLng(), lastEmployeeTrack.getLat(), lastEmployeeTrack.getLng());
            // 两坐标点距离
            newEmployeeTrack.setDistanceBetween(towPointDistance);
            //两点相差时间秒数
            Integer secondTimeDiffer = getTwoPointDifferTime(lastEmployeeTrack, newEmployeeTrack);
            newEmployeeTrack.setMoveSecond(secondTimeDiffer);

            QueryWrapper<RptEmployeeWork> employeeWorkQueryWrapper = new QueryWrapper<>();
            employeeWorkQueryWrapper.eq("employee_id", kfkDealEmployeeTo.getEmployee_id());
            employeeWorkQueryWrapper.eq("work_date", StringUtils.dateToStr(kfkDealEmployeeTo.getDate(), "yyyy-MM-dd"));
            List<RptEmployeeWork> rptEmployeeWorkList = rptEmployeeWorkMapper.selectList(employeeWorkQueryWrapper);

            for (RptEmployeeWork rptEmployeeWork : rptEmployeeWorkList) {
                if (rptEmployeeWork.getPlanStartTime().compareTo(kfkDealEmployeeTo.getDate()) <= 0 && rptEmployeeWork.getPlanEndTime().compareTo(kfkDealEmployeeTo.getDate()) >= 0) {
                    Grid grid = gridMap.get(rptEmployeeWork.getGridId());
                    if (null != grid) {
                        // 判断是否在网格
                        is_in_grid = DistanceUtils.insideGrid(Double.valueOf(kfkDealEmployeeTo.getLng()), Double.valueOf(kfkDealEmployeeTo.getLat()), grid);
                        if (is_in_grid) {
                            newEmployeeTrack.setGridId(grid.getGridId());
//                            staffClockIn(kfkDealEmployeeTo.getEmployee_id(), kfkDealEmployeeTo.getDate(), locationUtil.getAddress(kfkDealEmployeeTo.getLng(), kfkDealEmployeeTo.getLat()));
                            //更新人员在岗
                            if (null != tlEmployee) {
                                tlEmployee.setOnguardstatus(0);
//                                tlEmployee.setAttendance(0);
                                tlEmployeeMapper.updateById(tlEmployee);
                            }
                            //更新设施开门时间
                            updateOpenDoor(rptEmployeeWork, tlEmployeeMap, kfkDealEmployeeTo);
                        } else {
                            //更新人员离岗
                            if (null != tlEmployee) {
                                tlEmployee.setOnguardstatus(1);
                                tlEmployeeMapper.updateById(tlEmployee);
                            }
                        }
                    } else {
                        break;
                    }


                }
            }
            //更新是人员是否移动
            updateMove(tlEmployee, kfkDealEmployeeTo, lastEmployeeTrack, newEmployeeTrack);
            //加起来，或者是用或
            if (newEmployeeTrack.getDangerLowElectric() > 0) {
                newEmployeeTrack.setIsDanger(1);
            }
            if (newEmployeeTrack.getWarningStay() + newEmployeeTrack.getWarningLeave() + newEmployeeTrack.getWarningTogether() > 0) {
                newEmployeeTrack.setIsWarning(1);
            }
        } catch (NumberFormatException e) {
            log.error(e.getMessage(), e);
        } finally {
            String toDate = DateUtil.formatDate(newEmployeeTrack.getTimestamp());

            if (isInsert) {
                System.out.println("isDanger==================" + newEmployeeTrack.getIsDanger());
                employeeTrackMapper.insert(newEmployeeTrack);
                //该人员当天最后一条轨迹数据
                RedisUtil.set(EmployeeTrackLastOneKeyToday.token, newEmployeeTrack.getEmployeeId() + "_" + toDate, newEmployeeTrack);
                //该人员永久最后一条轨迹数据
                RedisUtil.set(EmployeeTrackLastOneKey.token, newEmployeeTrack.getEmployeeId(), newEmployeeTrack);
                //保存人员轨迹到redis，轨迹纠偏功能使用
                RedisUtil.setList(EmployeeTrackNoReviseListKey.token, newEmployeeTrack.getEmployeeId(), newEmployeeTrack);
                //保存设备在线状态
                RedisUtil.set(EquipOnlineKey.token, newEmployeeTrack.getEqpNum(), new JSONObject());
                //自动打卡

            }
        }
    }

    /**
     * 自动打卡
     */
//    public void autoPunch() {
//        employeePunchCardMapper.selectList()
//
//        return employeeTrack;
//    }

    public EmployeeTrack setLastEmployeeTrack(
            TlEmployee tlEmployee, EmployeeTrack newEmployeeTrack) {
        QueryWrapper<EmployeeTrack> employeeTrackQueryWrapper = null;
        if (null != tlEmployee) {
            employeeTrackQueryWrapper = new QueryWrapper<>();
            employeeTrackQueryWrapper.lambda().groupBy(EmployeeTrack::getTimestamp);
            employeeTrackQueryWrapper.lambda().eq(EmployeeTrack::getEmployeeId, tlEmployee.getId());
            employeeTrackQueryWrapper.lambda().last("limit 1");
            EmployeeTrack employeeTrack = employeeTrackMapper.selectOne(employeeTrackQueryWrapper);
        }
        EmployeeTrack employeeTrack = employeeTrackMapper.selectOne(employeeTrackQueryWrapper);
        //如果没有上次定位则代表是刚开始执行
        if (employeeTrack == null) {
            //图简单，懒得判断上次有没有数据了，理论上结果是一样的，取默认值的话，相当于上次数据为正常
            employeeTrack = newEmployeeTrack;
        }

        return employeeTrack;
    }

    public void updateMove(TlEmployee tlEmployee, KfkDealEmployeeTo kfkDealEmployeeTo, EmployeeTrack lastEmployeeTrack, EmployeeTrack newEmployeeTrack) {
        //停留状态
        boolean stayFlag = locationUtil.checkTwoPointSame(kfkDealEmployeeTo.getLng(), kfkDealEmployeeTo.getLat(), lastEmployeeTrack.getLng(), lastEmployeeTrack.getLat());

        if (null != tlEmployee) {
            if (!stayFlag) {
                newEmployeeTrack.setMoveSecond(lastEmployeeTrack.getMoveSecond() + 30);
                tlEmployee.setMove("0");
            } else {
                tlEmployee.setMove("1");
            }
            //更新工种
            TlWorkType tlWorkType = tlWorkTypeMapper.selectById(tlEmployee.getWorktype());
            if (Objects.nonNull(tlWorkType)) {
                tlEmployee.setWorktypename(tlWorkType.getWorktype());
            }

            SysDepart sysDepart = sysDepartMapper.selectById(tlEmployee.getDeptid());
            if (Objects.nonNull(sysDepart)) {
                tlEmployee.setEmpldeptname(sysDepart.getDepartName());
            }
            tlEmployeeMapper.updateById(tlEmployee);
        }

    }

    public EmployeeTrack crateEmployeeTrack(KfkDealEmployeeTo kfkDealEmployeeTo) {

        EmployeeTrack newEmployeeTrack = new EmployeeTrack();
        String employeeTrackId = StringUtils.uuid();
        newEmployeeTrack.setId(employeeTrackId);
        newEmployeeTrack.setEqpType(kfkDealEmployeeTo.getEqp_type());
        newEmployeeTrack.setEqpNum(kfkDealEmployeeTo.getEquanum());
        newEmployeeTrack.setWorkMonth(StringUtils.dateToStr(kfkDealEmployeeTo.getDate(), "yyyy-MM"));
        newEmployeeTrack.setWorkDay(kfkDealEmployeeTo.getDate());
        newEmployeeTrack.setEmployeeId(kfkDealEmployeeTo.getEmployee_id());
        newEmployeeTrack.setGridId("");
        newEmployeeTrack.setShiftId("");
        newEmployeeTrack.setLng(kfkDealEmployeeTo.getLng());
        newEmployeeTrack.setLat(kfkDealEmployeeTo.getLat());
        newEmployeeTrack.setLocation(kfkDealEmployeeTo.getLng() + "," + kfkDealEmployeeTo.getLat());
        String currentAddress = locationUtil.getAddress(kfkDealEmployeeTo.getLng(), kfkDealEmployeeTo.getLat());
        if (StringUtils.isNotEmpty(currentAddress)) {
            newEmployeeTrack.setAddress(currentAddress);
        } else {
            newEmployeeTrack.setAddress("");
        }
        newEmployeeTrack.setTimestamp(kfkDealEmployeeTo.getDate());
        newEmployeeTrack.setMessage("");
        newEmployeeTrack.setCreateTime(new Date());
        newEmployeeTrack.setIsDanger(0);
        newEmployeeTrack.setIsWarning(0);
        newEmployeeTrack.setWarningLeave(0);
        newEmployeeTrack.setWarningStay(0);
        newEmployeeTrack.setDangerLowElectric(0);
        newEmployeeTrack.setWarningTogether(0);
        newEmployeeTrack.setWarningTogetherIds("");
        newEmployeeTrack.setMoveSecond(0);
        newEmployeeTrack.setSpeed(kfkDealEmployeeTo.getSpeed());
        return newEmployeeTrack;
    }



//    public void employeeAlarmAndViolation(TlEmployee tlEmployee, KfkDealEmployeeTo kfkDealEmployeeTo, EmployeeTrack newEmployeeTrack) {
//
//        if (null != tlEmployee) {
//
//            //是否应急
//            boolean isEmergency = kfkHandleService.isEmergency(tlEmployee.getName(), "emp", kfkDealEmployeeTo.getDate());
//            if (isEmergency) {
//                newEmployeeTrack.setIsEmergency(1);
//            } else {
//                newEmployeeTrack.setIsEmergency(0);
//                // 报警处理
//                PerformanceMonitor.begin("-----------------------人员报警处理------------------~");
//                //todo
//                List<TlThreshold> tlThresholdList = getThresholdsFromRedis(kfkDealEmployeeTo.getEmployee_id());
//                for (TlThreshold tlThreshold : tlThresholdList) {
//                    switch (tlThreshold.getSysname()) {
//                        case "设备低电":
//                            /**
//                             if (newEmployeeTrack.getDangerLowElectric() > 0) {
//                             AlarmPerson alarmPerson = new AlarmPerson();
//                             newEmployeeTrack.setMessage("设备低电:" + lastEmployeeTrack.getDangerLowElectric() + 30 + "秒");
//                             alarmPerson.setAlarmPersonId(StringUtils.uuid());
//                             alarmPerson.setPersonId(newEmployeeTrack.getEmployeeId());
//                             alarmPerson.setPersonName(tlEmployee.getName());
//                             alarmPerson.setDepId(tlEmployee.getDeptid());
//                             alarmPerson.setAlarmTypeId(tlThreshold.getId());
//                             alarmPerson.setAlarmTypeName("设备低电");
//                             alarmPerson.setLng(lng);
//                             alarmPerson.setLat(lat);
//                             alarmPerson.setAddress(newEmployeeTrack.getAddress());
//                             alarmPerson.setAlarmTime(date);
//                             alarmPerson.setContent("设备低电" + lastEmployeeTrack.getDangerLowElectric() + 30 + "秒");
//                             alarmPerson.setCreateTime(new Date());
//                             alarmPersonMapper.insert(alarmPerson);
//                             sendEmployeeAlarm(lng, lat, date, tlEmployee, tlWorkType, newEmployeeTrack.getAddress(), newEmployeeTrack.getId(), "2", "person_alarm_low_power");
//                             }**/
//                            break;
//                        default:
//                            break;
//                    }
//                }
//                PerformanceMonitor.end();
//                //违规处理
//                PerformanceMonitor.begin("-----------------------人员违规处理------------------~");
//                if (is_in_worktime && null != workRule && "1".equals(workRule.getIsEnable()) && !CollectionUtils.isEmpty(workRuleItemList)) {
//                    AbnormalResult abnormalResult = new AbnormalResult();
//
//                    for (WorkRuleItem workRuleItem : workRuleItemList) {
//                        String sysname = workRuleItem.getSysName();
//                        String ruleCcontent = workRuleItem.getContent();
//                        JSONObject contentJson = JSON.parseObject(ruleCcontent);
//
//                        switch (sysname) {
//                            case "停留":
//                                if (0 == workRuleItem.getIsEnable()) {
//                                    break;
//                                }
//                                //不在网格内不报违规
//                                if (!is_in_grid) {
//                                    //停留违规持续时间秒
//                                    RedisUtil.set(PersonViolationStopTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, 0);
//                                    break;
//                                }
//                                //停留时间限制，分钟
//                                int tl = Integer.parseInt(String.valueOf(contentJson.get("time")));
//                                //查询停留时间内的所有设备记录
//                                QueryWrapper<EmployeeTrack> queryWrapper = new QueryWrapper<>();
//                                queryWrapper.lambda().eq(EmployeeTrack::getEmployeeId, newEmployeeTrack.getEmployeeId());
//                                String starttime = StringUtils.DateFormat(new Date(date.getTime() - 1000 * 60 * tl));
//                                String endtime = StringUtils.DateFormat(date);
//                                if (StringUtils.isNotEmpty(starttime) && StringUtils.isNotEmpty(endtime)) {
//                                    queryWrapper.lambda().between(EmployeeTrack::getTimestamp, starttime, endtime);
//                                }
//                                List<EmployeeTrack> employeeTracks = employeeTrackMapper.selectList(queryWrapper);
//                                Boolean isStop = true;
//                                if (Objects.isNull(employeeTracks) || employeeTracks.size() == 0) {
//                                    isStop = false;
//                                } else {
//                                    for (EmployeeTrack emp : employeeTracks
//                                    ) {
//                                        //停留范围限制米
//                                        BigDecimal scope = new BigDecimal(String.valueOf(contentJson.get("scope")));
//                                        //距离上一次数据的间隔距离
//                                        BigDecimal distance = new BigDecimal(locationUtil.getDistance(lng, lat, emp.getLng(), emp.getLat()));
//                                        if (distance.compareTo(scope) > 0) {
//                                            isStop = false;
//                                        }
//                                    }
//                                }
//
//                                if (isStop) {
//                                    //停留违规持续时间秒
//                                    int personViolationStopTime = Objects.nonNull(RedisUtil.get(PersonViolationStopTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class)) ? RedisUtil.get(PersonViolationStopTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class) + twoPointTimeDiffer : twoPointTimeDiffer;
//                                    RedisUtil.set(PersonViolationStopTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, personViolationStopTime);
//
//                                    abnormalResult = savePersonViolation(newEmployeeTrack, tlEmployee, workRuleItem, new Date(date.getTime() - 1000 * tl * 60), date);
//
//                                    newEmployeeTrack.setIsStop(1);
//                                    newEmployeeTrack.setIsWarning(1);
//                                    newEmployeeTrack.setWarningStay(lastEmployeeTrack.getWarningStay() + 30);
//                                    newEmployeeTrack.setLastMessageCheck("warningStay");
//                                    newEmployeeTrack.setMessage(abnormalResult.getMessage());
//
//                                    if (2 == abnormalResult.getIskeep()) {
//                                        sendEmployeeAlarm(lng, lat, date, tlEmployee, tlWorkType, newEmployeeTrack.getAddress(), abnormalResult.getId(), CommonConstant.PUSH_TYPE_VIOLATION, "person_violation_stay");
//                                    }
//                                } else {
//                                    //停留违规持续时间秒
//                                    RedisUtil.set(PersonViolationStopTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, 0);
//                                }
//                                break;
//                            case "离岗":
//                                if (0 == workRuleItem.getIsEnable()) {
//                                    break;
//                                }
//                                //允许出多少次
//                                Integer yxc = Objects.nonNull(contentJson.get("yxc")) ? Integer.parseInt(contentJson.get("yxc").toString()) : 2;
//                                //出网格判定多少秒
//                                Integer cwgpd = Objects.nonNull(contentJson.get("cwgpd")) ? Integer.parseInt(contentJson.get("cwgpd").toString()) * 60 : 20 * 60;
//                                //单次最长多少秒
//                                Integer dczc = Objects.nonNull(contentJson.get("dczc")) ? Integer.parseInt(contentJson.get("dczc").toString()) * 60 : 5 * 60;
//
//                                /*离岗：单次考勤时间段内：
//                                单次最长时间内，则不报警，次数不限；
//                                单次最长时间外 至 出网格判断时间内，允许2次机会，超过机会后报警；
//                                超过出网格判断时间，则立即报警。*/
//                                if (!is_in_grid) {
//                                    //离岗违规持续时间秒
//                                    int personViolationDemobilizTime = Objects.nonNull(RedisUtil.get(PersonViolationDemobilizTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class)) ? RedisUtil.get(PersonViolationDemobilizTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class) + twoPointTimeDiffer : twoPointTimeDiffer;
//                                    RedisUtil.set(PersonViolationDemobilizTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, personViolationDemobilizTime);
//
//                                    if (personViolationDemobilizTime >= cwgpd) {
//                                        abnormalResult = savePersonViolation(newEmployeeTrack, tlEmployee, workRuleItem, new Date(date.getTime() - 1000 * cwgpd), date);
//
//                                        newEmployeeTrack.setIsDemobiliz(1);
//                                        newEmployeeTrack.setIsWarning(1);
////                                        newEmployeeTrack.setWarningLeave(lastEmployeeTrack.getWarningLeave() + 30);
//                                        newEmployeeTrack.setWarningLeave(personViolationDemobilizTime);
//                                        newEmployeeTrack.setMessage(abnormalResult.getMessage());
//                                        newEmployeeTrack.setLastMessageCheck("warningLeave");
//
//                                        if (2 == abnormalResult.getIskeep()) {
//                                            sendEmployeeAlarm(lng, lat, date, tlEmployee, tlWorkType, newEmployeeTrack.getAddress(), abnormalResult.getId(), CommonConstant.PUSH_TYPE_VIOLATION, "person_violation_stay");
//                                        }
//                                    } else if (personViolationDemobilizTime > dczc && personViolationDemobilizTime < cwgpd) {
//
//                                        //该人员正常在网格的次数
//                                        int personViolationInGridFlag = Objects.nonNull(RedisUtil.get(PersonViolationInGridFlagKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class)) ? RedisUtil.get(PersonViolationInGridFlagKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class) : 1;
//                                        if (1 == personViolationInGridFlag) {
//                                            //该人员违规是否在网格内
//                                            RedisUtil.set(PersonViolationInGridFlagKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, 0);
//                                            //该人员当次考勤不在网格的次数
//                                            RedisUtil.set(PersonViolationNotInGridNumKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, (Objects.nonNull(RedisUtil.get(PersonViolationNotInGridNumKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class)) ? RedisUtil.get(PersonViolationNotInGridNumKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class) + 1 : 1));
//                                        }
//                                        int personViolationNotInGridNum = Objects.nonNull(RedisUtil.get(PersonViolationNotInGridNumKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class)) ? RedisUtil.get(PersonViolationNotInGridNumKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class) + 1 : 1;
//                                        if (personViolationNotInGridNum > yxc) {
//                                            abnormalResult = savePersonViolation(newEmployeeTrack, tlEmployee, workRuleItem, new Date(date.getTime() - 1000 * personViolationDemobilizTime), date);
//
//                                            newEmployeeTrack.setIsDemobiliz(1);
//                                            newEmployeeTrack.setIsWarning(1);
//                                            newEmployeeTrack.setWarningLeave(lastEmployeeTrack.getWarningLeave() + 30);
//                                            newEmployeeTrack.setMessage(abnormalResult.getMessage());
//                                            newEmployeeTrack.setLastMessageCheck("warningLeave");
//
//                                            if (2 == abnormalResult.getIskeep()) {
//                                                sendEmployeeAlarm(lng, lat, date, tlEmployee, tlWorkType, newEmployeeTrack.getAddress(), abnormalResult.getId(), CommonConstant.PUSH_TYPE_VIOLATION, "person_violation_stay");
//                                            }
//                                        }
//                                    }
//                                } else {
//                                    //该人员违规离岗的持续时间
//                                    RedisUtil.set(PersonViolationDemobilizTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, 0);
//                                    //该人员违规是否在网格内
//                                    RedisUtil.set(PersonViolationInGridFlagKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, 1);
//                                }
//                                break;
//                            case "聚众":
//                                if (0 == workRuleItem.getIsEnable()) {
//                                    break;
//                                }
//                                //聚众人数
//                                Integer rs = Integer.parseInt(contentJson.get("rs").toString());
//                                //聚众范围米
//                                Integer scope = Integer.parseInt(contentJson.get("scope").toString());
//                                //聚众时间
//                                Integer time = Integer.parseInt(contentJson.get("time").toString());
//                                // 聚众
//                                QueryWrapper<TlEmployee> employeeQueryWrapper = new QueryWrapper<>();
//                                employeeQueryWrapper.ne("id", employee_id);
////                                employeeQueryWrapper.eq("onguardstatus", "0");
//                                employeeQueryWrapper.eq("bindstatus", "1");
//                                employeeQueryWrapper.ne("addr", "");
//                                employeeQueryWrapper.like("addr", ",");
//                                employeeQueryWrapper.eq("status", "1");
//                                List<TlEmployee> employeeList = tlEmployeeMapper.selectList(employeeQueryWrapper);
//                                int people = 0;
//                                String warning_together_ids = "";
//                                for (TlEmployee employee : employeeList) {
//                                    if (StringUtils.isNotEmpty(employee.getAddr())) {
//                                        double location_distance = locationUtil.getDistance(lng, lat, employee.getAddr().split(",")[0], employee.getAddr().split(",")[1]);
//                                        if (location_distance < scope) {
//                                            people++;
//                                            warning_together_ids += employee.getId() + ",";
//                                            if (people > (rs - 1)) {
//                                                break;
//                                            }
//                                        }
//                                    }
//                                }
//                                if (people >= (rs - 1)) {
//                                    //聚众违规持续时间秒
//                                    int personViolationGatherTime = Objects.nonNull(RedisUtil.get(PersonViolationGatherTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class)) ? RedisUtil.get(PersonViolationGatherTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, int.class) + twoPointTimeDiffer : twoPointTimeDiffer;
//                                    RedisUtil.set(PersonViolationGatherTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, personViolationGatherTime);
//
//                                    if (personViolationGatherTime >= time * 60) {
//                                        abnormalResult = savePersonViolation(newEmployeeTrack, tlEmployee, workRuleItem, new Date(date.getTime() - 1000 * time * 60), date);
//
//                                        newEmployeeTrack.setIsGather(1);
//                                        newEmployeeTrack.setWarningTogether(lastEmployeeTrack.getWarningTogether() + 30);
//                                        newEmployeeTrack.setWarningTogetherIds(warning_together_ids);
//                                        newEmployeeTrack.setLastMessageCheck("warningTogether");
//                                        newEmployeeTrack.setMessage(abnormalResult.getMessage());
//
//                                        if (2 == abnormalResult.getIskeep()) {
//                                            sendEmployeeAlarm(lng, lat, date, tlEmployee, tlWorkType, newEmployeeTrack.getAddress(), abnormalResult.getId(), CommonConstant.PUSH_TYPE_VIOLATION, "person_violation_stay");
//                                        }
//                                    }
//                                } else {
//                                    RedisUtil.set(PersonViolationGatherTimeKeyToday.token, newEmployeeTrack.getEmployeeId() + rptEmployeeWorkId + "_" + today, 0);
//                                }
//                                break;
//                            default:
//                                break;
//                        }
//                        //doEmployeeWork(inGrid, inWork);
//                    }
//                }
//                PerformanceMonitor.end();
//            }
//        }
//    }

    public void updateOpenDoor(RptEmployeeWork rptEmployeeWork, Map<String, TlEmployee> tlEmployeeMap, KfkDealEmployeeTo kfkDealEmployeeTo) {
        //更新设施开门时间
        TlEmployee tlEmployee = tlEmployeeMap.get(rptEmployeeWork.getEmployeeId());
        if (null != tlEmployee) {
            QueryWrapper<TlFacilities> tlFacilitiesQueryWrapper = new QueryWrapper<>();
            tlFacilitiesQueryWrapper.lambda().eq(TlFacilities::getPrincipal, tlEmployee.getBindaccount());
            tlFacilitiesQueryWrapper.lambda().eq(TlFacilities::getFaclstatus, 0);
            List<TlFacilities> tlFacilitiesList = tlFacilitiesMapper.selectList(tlFacilitiesQueryWrapper);
            for (TlFacilities tlFacilities : tlFacilitiesList) {
                tlFacilities.setOpenTime(kfkDealEmployeeTo.getDate());
                tlFacilitiesMapper.updateById(tlFacilities);
            }
        }
    }

    /**
     * 更新人员违规异常表
     *
     * @param newEmployeeTrack
     * @param tlEmployee
     * @param workRuleItem
     * @param alarmStartTime
     * @param alarmEndTime
     * @return
     */
    private AbnormalResult insertPersonViolation(EmployeeTrack newEmployeeTrack, TlEmployee tlEmployee, WorkRuleItem workRuleItem, Date alarmStartTime, Date alarmEndTime) {
        AbnormalResult abnormalResult = new AbnormalResult();
        String today = DateUtil.formatDate(alarmStartTime);
        DlbjViolation dlbjViolation1 = RedisUtil.get(PersonViolationTypeNameLastOneKeyToday.token, newEmployeeTrack.getEmployeeId() + "_" + workRuleItem.getSysName() + "_" + today, DlbjViolation.class);

        if (Objects.nonNull(dlbjViolation1) && dlbjViolation1.getDate().compareTo(alarmEndTime) == 0) {
            abnormalResult.setMessage(dlbjViolation1.getContent());
            return abnormalResult;
        }

        DlbjViolation dlbjViolation = new DlbjViolation();
        dlbjViolation.setDlbjViolationId(StringUtils.uuid());
        dlbjViolation.setPersonId(newEmployeeTrack.getEmployeeId());
        dlbjViolation.setPersonName(tlEmployee.getName());
        dlbjViolation.setPersonTypeId(tlEmployee.getWorktype());
        dlbjViolation.setPersonTypeName(tlEmployee.getWorktypename());
        dlbjViolation.setDepid(tlEmployee.getDeptid());
        dlbjViolation.setDepName(tlEmployee.getEmpldeptname());
        dlbjViolation.setLng(newEmployeeTrack.getLng());
        dlbjViolation.setLat(newEmployeeTrack.getLat());
        dlbjViolation.setDate(alarmEndTime);
        dlbjViolation.setAddress(newEmployeeTrack.getAddress());
        dlbjViolation.setDuration(String.valueOf(newEmployeeTrack.getWarningStay()));
        dlbjViolation.setViolationTypeId(workRuleItem.getRuleId());
        dlbjViolation.setViolationTypeName(workRuleItem.getSysName());
        dlbjViolation.setCreateTime(new Date());
        dlbjViolation.setViolationStartTime(alarmStartTime);
        dlbjViolation.setViolationEndTime(alarmEndTime);

        dlbjViolation.setEmployeeTrackStartId(newEmployeeTrack.getId());
        dlbjViolation.setEmployeeTrackEndId(newEmployeeTrack.getId());

        int duration = StringUtils.calLastedTime(dlbjViolation.getViolationStartTime(), alarmEndTime);
        String time = StringUtils.s2date(Long.parseLong(String.valueOf(duration)));
        String dangerDesc = "";

        if ("停留".equals(dlbjViolation.getViolationTypeName())) {
            dangerDesc = "人员停留违规, 停留时长" + time;
            dlbjViolation.setViolationValue(new BigDecimal(duration));
            dlbjViolation.setIsStop(1);
        }
        if ("离岗".equals(dlbjViolation.getViolationTypeName())) {
            dangerDesc = "人员离岗违规, 离岗时长" + time;
            dlbjViolation.setViolationValue(new BigDecimal(duration));
            dlbjViolation.setIsDemobiliz(1);
        }
        if ("聚众".equals(dlbjViolation.getViolationTypeName())) {
            dangerDesc = "人员聚众违规,聚众时长" + time;
            dlbjViolation.setViolationValue(new BigDecimal(duration));
            dlbjViolation.setIsGather(1);
        }

        dlbjViolation.setContent(dangerDesc);
        int insert = dlbjViolationMapper.insert(dlbjViolation);
        if (insert > 0) {
            abnormalResult.setIskeep(2);
        }
        abnormalResult.setId(dlbjViolation.getDlbjViolationId());
        abnormalResult.setMessage(dangerDesc);

        //保存插入后的数据
        RedisUtil.set(PersonViolationTypeNameLastOneKeyToday.token, dlbjViolation.getPersonId() + "_" + dlbjViolation.getViolationTypeName() + "_" + today, dlbjViolation);
        return abnormalResult;
    }

    /**
     * 人员违规更新数据
     *
     * @param dlbjViolation
     * @param date
     */
    private AbnormalResult updatePersonViolation(String personId, DlbjViolation dlbjViolation, Date date) {
        AbnormalResult abnormalResult = new AbnormalResult();
        String dangerDesc = "";
        String today = DateUtil.formatDate(date);
        int duration = StringUtils.calLastedTime(dlbjViolation.getViolationStartTime(), date);
        String time = StringUtils.s2date(Long.parseLong(String.valueOf(duration)));

        if ("停留".equals(dlbjViolation.getViolationTypeName())) {
            dangerDesc = "人员停留违规, 停留时长" + time;
            dlbjViolation.setViolationValue(new BigDecimal(duration));
            dlbjViolation.setIsStop(1);
        }
        if ("离岗".equals(dlbjViolation.getViolationTypeName())) {
            dangerDesc = "人员离岗违规, 离岗时长" + time;
            dlbjViolation.setViolationValue(new BigDecimal(duration));
            dlbjViolation.setIsDemobiliz(1);
        }
        if ("聚众".equals(dlbjViolation.getViolationTypeName())) {
            dangerDesc = "人员聚众违规,聚众时长" + time;
            dlbjViolation.setViolationValue(new BigDecimal(duration));
            dlbjViolation.setIsGather(1);
        }
        dlbjViolation.setContent(dangerDesc);
        dlbjViolation.setViolationEndTime(date);
        dlbjViolation.setIsKeep(1);

        int i = dlbjViolationMapper.updateById(dlbjViolation);
        RedisUtil.set(PersonViolationTypeNameLastOneKeyToday.token, personId + "_" + dlbjViolation.getViolationTypeName() + "_" + today, dlbjViolation);

        abnormalResult.setId(dlbjViolation.getDlbjViolationId());
        abnormalResult.setMessage(dangerDesc);
        abnormalResult.setIskeep(i);
        return abnormalResult;
    }


    public WorkKaoqin getKaoqin(Date now, String groupId) {
//        Date now = new Date();
        WorkGroup workGroup = workGroupMapper.selectById(groupId);
        if (null == workGroup) {
            return null;
        }
        //勤类型，固定班1，冬夏班2
        Integer kaoqinType = workGroup.getKaoqinType();
        //1:夏季,2:冬季
        String season = DateUtils.getCurrentSeason(now);
        List<WorkKaoqin> workKaoqinList = workKaoqinMapper.selectBatchIds(Arrays.asList(workGroup.getKaoqinIds().split(",")));
        for (WorkKaoqin workKaoqin : workKaoqinList) {
            String planStartTime = null;//排班开始时间
            String planEndTime = null;//排班结束时间
            if (1 == kaoqinType) {//固定班
                planStartTime = workKaoqin.getSbsj();
                planEndTime = workKaoqin.getXbsj();
            } else if (2 == kaoqinType) {//冬夏班
                if ("summer".equals(season)) {
                    planStartTime = workKaoqin.getXsbsj();
                    planEndTime = workKaoqin.getXxbsj();
                } else if ("winter".equals(season)) {
                    planStartTime = workKaoqin.getDsbsj();
                    planEndTime = workKaoqin.getDxbsj();
                }
            }
            boolean existFlag = DateUtil.isIn(now, DateUtil.parse(planStartTime), DateUtil.parse(planEndTime));
            if (existFlag) {
                return workKaoqin;
            }
        }
        return null;
    }


    public void sendEmployeeAlarm(String lng, String lat, Date date, TlEmployee tlEmployee, TlWorkType tlWorkType, String currentAddress, String targetId, Integer model, String sysname) {

        QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(sysUserRoleQueryWrapper);
        Map<String, List<SysUserRole>> sysUserRoleMap = sysUserRoleList.stream().collect(Collectors.groupingBy(SysUserRole::getUserid));

        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        List<SysRole> sysRoleList = sysRoleMapper.selectList(sysRoleQueryWrapper);
        Map<String, SysRole> sysRoleMap = sysRoleList.stream().collect(Collectors.groupingBy(SysRole::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));
        JSONObject alarmJson = new JSONObject();
        alarmJson.put("model", model);
        JSONObject detailJson = new JSONObject();
        detailJson.put("id", targetId);
        detailJson.put("check", sysname);
        detailJson.put("happenTime", date);
        detailJson.put("lng", lng);
        detailJson.put("lat", lat);
        detailJson.put("address", currentAddress);
        detailJson.put("pic", tlEmployee.getPersonphoto());
        detailJson.put("typeId", tlWorkType.getId());
        detailJson.put("typeName", tlWorkType.getWorktype());
        detailJson.put("authorId", tlEmployee.getId());
        detailJson.put("authorName", tlEmployee.getName());
        detailJson.put("authorType", "person");
        alarmJson.put("detail", detailJson);
//        List<SysUserRole> sysUserRoleList2 = sysUserRoleMap.get(user1.getUid());
//        if (null != sysUserRoleList2) {
//            for (SysUserRole sysUserRole : sysUserRoleList2) {
//                SysRole sysRole = sysRoleMap.get(sysUserRole.getRoleid());
//                if (null != sysRole) {
//                    if (!sysRole.getRoleName().equals("管理员")) {
        WebSocketUtils.sendMessageToOne(alarmJson.toString(), tlEmployee.getBindaccount());
//                    }
//                }
//            }
//        }
        TlEmployee tlEmployee1 = tlEmployeeMapper.selectById(tlEmployee.getId());
        if (null != tlEmployee1) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().notIn(User::getUid, tlEmployee1.getBindaccount());
            List<User> userList = userMapper.selectList(userQueryWrapper);
            for (User user : userList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("model", model);
                JSONObject object = new JSONObject();
                object.put("id", targetId);
                object.put("check", sysname);
                object.put("happenTime", date);
                object.put("lng", lng);
                object.put("lat", lat);
                object.put("address", currentAddress);
                object.put("pic", tlEmployee.getPersonphoto());
                object.put("typeId", tlWorkType.getId());
                object.put("typeName", tlWorkType.getWorktype());
                object.put("authorId", tlEmployee.getId());
                object.put("authorName", tlEmployee.getName());
                object.put("authorType", "person");
                jsonObject.put("detail", object);
                List<SysUserRole> sysUserRoleList1 = sysUserRoleMap.get(user.getUid());
                if (null != sysUserRoleList1) {
                    for (SysUserRole sysUserRole : sysUserRoleList1) {
                        SysRole sysRole = sysRoleMap.get(sysUserRole.getRoleid());
                        if (null != sysRole) {
                            if (sysRole.getRoleName().equals("管理员")) {
                                WebSocketUtils.sendMessageToOne(jsonObject.toString(), sysUserRole.getUserid());
                            }
                        }
                    }
                }
            }
        }
    }

    public AbnormalResult savePersonViolation(EmployeeTrack newEmployeeTrack, TlEmployee tlEmployee, WorkRuleItem workRuleItem, Date alarmStartTime, Date alarmEndTime) {
        String today = DateUtil.formatDate(alarmStartTime);
        DlbjViolation dlbjViolation = RedisUtil.get(PersonViolationTypeNameLastOneKeyToday.token, newEmployeeTrack.getEmployeeId() + "_" + workRuleItem.getSysName() + "_" + today, DlbjViolation.class);
        if (Objects.isNull(dlbjViolation)) {
            String day = DateUtil.formatDate(new Date());
            String startTime = AttributeUtils.timeCompletion(day, 's');
            String endTime = AttributeUtils.timeCompletion(day, 'e');

            QueryWrapper<DlbjViolation> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(DlbjViolation::getPersonId, newEmployeeTrack.getEmployeeId());
            queryWrapper.lambda().eq(DlbjViolation::getViolationTypeName, workRuleItem.getSysName());
            queryWrapper.lambda().between(DlbjViolation::getDate, startTime, endTime);
            queryWrapper.lambda().orderByDesc(DlbjViolation::getDate);
            queryWrapper.lambda().last(" LIMIT 1");
            dlbjViolation = dlbjViolationMapper.selectOne(queryWrapper);
        }

        if (Objects.nonNull(dlbjViolation)) {
            //获取基数天数和检测时间间隔
            //聚合时间(分钟)
            int polymerizationtime = 0;
            if (Objects.nonNull(workRuleItem.getPolymerizationtime())) {
                polymerizationtime = workRuleItem.getPolymerizationtime();
            }
            Date date1 = new Date(alarmStartTime.getTime() - 1000 * 60 * polymerizationtime);
            if (date1.compareTo(dlbjViolation.getViolationEndTime()) > 0) {
                dlbjViolation = null;
            }
        }

        AbnormalResult abnormalResult = new AbnormalResult();
        if (Objects.nonNull(dlbjViolation)) {
            //过滤掉之前的时间
            if (alarmEndTime.compareTo(dlbjViolation.getViolationEndTime()) <= 0) {
                return abnormalResult;
            }

            abnormalResult = updatePersonViolation(newEmployeeTrack.getEmployeeId(), dlbjViolation, alarmEndTime);
        }
        if (1 != abnormalResult.getIskeep()) {
            abnormalResult = insertPersonViolation(newEmployeeTrack, tlEmployee, workRuleItem, alarmStartTime, alarmEndTime);
        }
        return abnormalResult;
    }

    /**
     * 机械清扫
     *
     * @param date
     * @param map1
     */
    public List<kfkDealCarWorkPlan> jxqsPlan(Date date, Map<String, Object> map1) {
        List<kfkDealCarWorkPlan> lwp = new ArrayList<>();
//        QueryWrapper<JxqsPlan> jxqsPlanQueryWrapper = new QueryWrapper<>();
//        jxqsPlanQueryWrapper.lambda().le(JxqsPlan::getYxsdStart, map1.get("date"));
//        jxqsPlanQueryWrapper.lambda().ge(JxqsPlan::getYxsdEnd, map1.get("date"));
//        jxqsPlanQueryWrapper.lambda().like(JxqsPlan::getCarIds, map1.get("car_id"));
//        List<JxqsPlan> jxqs = jxqsPlanMapper.selectList(jxqsPlanQueryWrapper);
//
//        for (JxqsPlan jxqs_item : jxqs) {
//            if (TimeUtil.checkPeriodDate(TimeUtil.formatDateStringToDate(date), TimeUtil.formatStringToDate(jxqs_item.getYxsdStart()), TimeUtil.formatStringToDate(jxqs_item.getYxsdEnd()), jxqs_item.getWorkPeriod())) {
//                kfkDealCarWorkPlan wp = new kfkDealCarWorkPlan();
//                wp.setId(jxqs_item.getJxqsPlanId());
//                wp.setPlanName(jxqs_item.getName());
//                wp.setGridId(jxqs_item.getGridId());
//                wp.setWorkTypeId(jxqs_item.getWorkTypeId());
//                wp.setWorkTypeName(jxqs_item.getWorkTypeName());
//                wp.setWorkSubTypeId(jxqs_item.getWorkSubTypeId());
//                wp.setWorkRuleId(jxqs_item.getWorkRuleId());
//                wp.setEstimateOil(jxqs_item.getDcyjyh());
//                wp.setEstimateWater(jxqs_item.getDcyjsh());
//                wp.setPerMinute(jxqs_item.getDczysc());
//                wp.setMileageProgress(jxqs_item.getLcwcd());
//                wp.setWayProgress(jxqs_item.getLjwcd());
//                wp.setWorkGroupId(jxqs_item.getWorkGroupId());
//                wp.setFrequency(jxqs_item.getTangci());
//                wp.setType(2);
//                lwp.add(wp);
//            }
//        }
        return lwp;
    }

    /**
     * 垃圾清运
     *
     * @param date
     * @param map1
     */
    public List<kfkDealCarWorkPlan> ljqyWorkPlan(Date date, Map<String, Object> map1) {
        List<kfkDealCarWorkPlan> lwp = new ArrayList<>();
//        QueryWrapper<LjqyWorkPlan> ljqyWorkPlanQueryWrapper = new QueryWrapper<>();
//        ljqyWorkPlanQueryWrapper.lambda().le(LjqyWorkPlan::getYxsdStartDate, map1.get("date"));
//        ljqyWorkPlanQueryWrapper.lambda().ge(LjqyWorkPlan::getYxsdEndDate, map1.get("date"));
//        ljqyWorkPlanQueryWrapper.lambda().eq(LjqyWorkPlan::getWorkCarId, map1.get("car_id"));
//        List<LjqyWorkPlan> ljqy = ljqyWorkPlanMapper.selectList(ljqyWorkPlanQueryWrapper);
//        for (LjqyWorkPlan item : ljqy) {
//            if (TimeUtil.checkPeriodDate(TimeUtil.formatDateStringToDate(date), TimeUtil.formatStringToDate(item.getYxsdStartDate()), TimeUtil.formatStringToDate(item.getYxsdEndDate()), item.getWorkCycle())) {
//                kfkDealCarWorkPlan wp = new kfkDealCarWorkPlan();
//                wp.setId(item.getLjqyWorkPlanId());
//                wp.setPlanName(item.getName());
//                wp.setGridId(item.getGridId());
//                wp.setWorkRuleId(item.getWorkRuleId());
//                wp.setPerMinute(item.getDczysc());
//                wp.setWorkGroupId(item.getWorkGroupId());
//                wp.setFrequency(1);
//                wp.setType(3);
//                lwp.add(wp);
//            }
//        }
        return lwp;
    }

    /**
     * 垃圾转运
     *
     * @param date
     * @param map1
     */
    public List<kfkDealCarWorkPlan> ljzyWorkPlan(Date date, Map<String, Object> map1) {
        List<kfkDealCarWorkPlan> lwp = new ArrayList<>();
//        QueryWrapper<LjzyWorkPlan> ljqyWorkPlanQueryWrapper = new QueryWrapper<>();
//        ljqyWorkPlanQueryWrapper.lambda().le(LjzyWorkPlan::getYxsdStartDate, map1.get("date"));
//        ljqyWorkPlanQueryWrapper.lambda().ge(LjzyWorkPlan::getYxsdEndDate, map1.get("date"));
//        ljqyWorkPlanQueryWrapper.lambda().eq(LjzyWorkPlan::getCarId, map1.get("car_id"));
//        List<LjzyWorkPlan> ljzy = ljzyWorkPlanMapper.selectList(ljqyWorkPlanQueryWrapper);
//        for (LjzyWorkPlan item : ljzy) {
//            if (TimeUtil.checkPeriodDate(TimeUtil.formatDateStringToDate(date), TimeUtil.formatStringToDate(item.getYxsdStartDate()), TimeUtil.formatStringToDate(item.getYxsdEndDate()), 1)) {
//                kfkDealCarWorkPlan wp = new kfkDealCarWorkPlan();
//
//                wp.setId(item.getLjzyWorkPlanId());
//                wp.setPlanName(item.getName());
//                wp.setGridId(item.getGridId());
//                wp.setWorkRuleId(item.getWorkRuleId());
//                wp.setWorkGroupId(item.getWorkGroupId());
//                wp.setFrequency(1);
//                wp.setType(4);
//                lwp.add(wp);
//            }
//        }
        return lwp;
    }


    public List<TlThreshold> getThresholdsFromRedis(String itemId) {
        List<TlThreshold> thresholdList = new ArrayList<>();
        try {
            List<JSONObject> listObject = RedisUtil.get(PersonAlarmKey.token, itemId, List.class);
            if (CollectionUtils.isEmpty(listObject)) {
                QueryWrapper<TlThreshold> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(TlThreshold::getItemid, itemId);
                queryWrapper.lambda().eq(TlThreshold::getStatus, "1");
                thresholdList = tlThresholdMapper.selectList(queryWrapper);
                RedisUtil.set(PersonAlarmKey.token, itemId, thresholdList);
            } else {
                for (JSONObject jsonObject : listObject) {
                    thresholdList.add(JSONObject.parseObject(JSONObject.toJSONString(jsonObject), TlThreshold.class));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return thresholdList;
    }

    //获取两点相差秒数
    public Integer getTwoPointDifferTime(EmployeeTrack preEmployeeTrack, EmployeeTrack currentEmployeeTrack) {
        Date preDate = preEmployeeTrack.getTimestamp();
        Date currentDate = currentEmployeeTrack.getTimestamp();
        double secondDiffer = DateUtil.between(preDate, currentDate, DateUnit.SECOND);
        return Double.valueOf(secondDiffer).intValue();
    }
}
